package meijuli.com.join51.business.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.activity.CertificationActivity;
import meijuli.com.join51.business.aliyun.ImageUtils;
import com.jhx.common.model.User;
import meijuli.com.join51.business.ui.widget.ClearEditText;
import meijuli.com.join51.business.utils.SoftInputUtil;
import com.jhx.common.utils.ToastUtil;
import com.jhx.common.utils.UserManager;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 营业执照认证
 *
 * @author wenqin 2017-04-14 14:07
 */
public class AttestCompanyFragment extends PhotoFragment implements ImageUtils.SelectImageListener{
    Button mNextBtn;
    ClearEditText mEditTop;
    ClearEditText mEditBottom;
    ImageView mTakePhonePositive;
    /**
     * 缓存用户信息
     */
    private User mUserInfo;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_attest_company, container, false);
        mNextBtn = view.findViewById(R.id.next_btn);
        mEditTop = view.findViewById(R.id.edit_name);
        mEditBottom = view.findViewById(R.id.edit_num);
        mTakePhonePositive = view.findViewById(R.id.take_phone_positive);
        mTakePhonePositive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onTakePhotoPositiveClick();
            }
        });
        mNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nextBtnClick();
            }
        });
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ((CertificationActivity)getActivity()).setToolbarTitle("商家认证");
        initView();
        initData();
    }

    private void initView() {
        mEditBottom.setInputType(InputType.TYPE_CLASS_TEXT);
        mEditBottom.setFilters(new InputFilter[]{new InputFilter.LengthFilter(60)});
    }

    private void initData() {
        // 检查User是否为空
        if (UserManager.get().checkUserNull(getActivity())) {
            return;
        }
        mUserInfo = UserManager.get().getUser();
        mEditBottom.setText(mUserInfo.getRegisterNum());
        Glide.with(this).load(mUserInfo.getLocalLicense())
                .error(R.mipmap.img_license).
                into(mTakePhonePositive);
        mPicPath1 = mUserInfo.getLicense();
        mLocalPicPath1 = mUserInfo.getLocalLicense();

        SoftInputUtil.get().hideSoftKeyboard(getActivity());
    }

    void onTakePhotoPositiveClick() {
        SoftInputUtil.get().hideSoftKeyboard(getActivity());
        toType = 1;
        showListDialog();
    }

    void nextBtnClick() {
        SoftInputUtil.get().hideSoftKeyboard(getActivity());

        if (mUserInfo.getType() == User.TYPE_ONLINE) {
            if (TextUtils.isEmpty(mEditTop.getText())) {
                ToastUtil.getInstance().showToast(getActivity(), "商户名称不能为空");
                return;
            }
            UserManager.get().setBusinessName(mEditTop.getText().toString());
            switchFragment(this, new AttestPersonFragment());
            return;
        }
        if (TextUtils.isEmpty(mEditTop.getText()) || TextUtils.isEmpty(mEditBottom.getText())) {
            ToastUtil.getInstance().showToast(getActivity(), "商户名称或注册号不能为空");
            return;
        }
        if (TextUtils.isEmpty(mLocalPicPath1)) {
            ToastUtil.getInstance().showToast(getActivity(), "照片不能为空");
            return;
        }
        if (TextUtils.isEmpty(mPicPath1) && mPicPath1.length() < 5) {
            ToastUtil.getInstance().showToast(getActivity(), "上传图片失败，请重新上传");
            return;
        }
        String businessNum = mEditBottom.getText().toString();
        if (!checkInput(businessNum)) {
            ToastUtil.getInstance().showToast(getActivity(), "注册号只能包含数字或字母");
            return;
        }

        // 保存数据
        UserManager.get()
                .setLicense(mPicPath1)
                .setBusinessName(mEditTop.getText().toString())
                .setRegisterNum(mEditBottom.getText().toString())
                .setLocalLicense(mLocalPicPath1);

        switchFragment(this, new AttestPersonFragment());
    }

    /**
     * 检测输入
     * 只允许字母、数字和汉字
     */
    private Boolean checkInput(String str) {
        Pattern pat = Pattern.compile("^[a-zA-Z0-9]+$");
        Matcher mat = pat.matcher(str);
        return mat.matches();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 以下方法将把权限结果执行给EasyPermission
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onUpLoadSuccess(String cloudKey, String sourceFilePath) {
        Glide.with(this).load(sourceFilePath).error(R.mipmap.img_default).into(mTakePhonePositive);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        ((CertificationActivity)getActivity()).setToolbarTitle("商家认证");
    }
}
